package com.ugoodtech.mdcc.core.utils;

import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Cesc on 2015/11/26.
 * 复制对象类
 */
public class BeanUtil extends BeanUtils {

//    private static Map cache = new HashMap();
//    private static Log logger = LogFactory.getFactory().getInstance(BeanUtilEx.class);

    private BeanUtil() {
    }

    static {
        // 注册sql.date的转换器，即允许BeanUtils.copyProperties时的源目标的sql类型的值允许为空
        ConvertUtils.register(new org.apache.commons.beanutils.converters.SqlDateConverter(null), java.sql.Date.class);
        // 注册util.date的转换器，即允许BeanUtils.copyProperties时的源目标的util类型的值允许为空
        ConvertUtils.register(new org.apache.commons.beanutils.converters.SqlDateConverter(null), java.util.Date.class);
        ConvertUtils.register(new org.apache.commons.beanutils.converters.SqlTimestampConverter(null), java.sql.Timestamp.class);
    }


    public static void copyProperties(Object source, Object target,String... properties) {
        // 支持对日期copy
        List<String> ignoreFields=new ArrayList<>();
        Class<?> clazz = source.getClass();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                ignoreFields.add(field.getName());
            }
        }

        ignoreFields.removeAll(Arrays.asList(properties));
        BeanUtils.copyProperties(source, target,ignoreFields.toArray(new String[ignoreFields.size()]));
    }
    public Object getDtoObject(Object source, String... properties) {
        // 支持对日期copy
        List<String> ignoreFields=new ArrayList<>();
        Class<?> clazz = source.getClass();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                ignoreFields.add(field.getName());
            }
        }
        Object dto;
        try {
            dto=clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
            return source;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return source;
        }
        ignoreFields.removeAll(Arrays.asList(properties));
        BeanUtils.copyProperties(source, dto,ignoreFields.toArray(new String[ignoreFields.size()]));
        return dto;
    }

}
